<template>
  <el-dialog :visible.sync="visible" width="70%" custom-class="default-dialog user-edit-dialog"
    :close-on-click-modal="false" @close="cancel" append-to-body>
    <div slot="title">
      <img v-if="type" :src="require(`@/assets/img/${type}.png`)" alt="">
      <span>{{ title }} </span>
    </div>
    <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="dialog-form" :disabled="type == 'view'">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="account" :disabled="type == 'edit' ? true : false">
            <el-input size="small" v-model="form.account"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="真实姓名" prop="realName">
            <el-input size="small" v-model="form.realName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickName">
            <el-input size="small" v-model="form.nickName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用" prop="isUseage">
            <el-switch v-model="form.isUseage" :active-value="1" :inactive-value="2"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobile">
            <el-input size="small" v-model.number="form.mobile"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="固定电话" prop="telephone">
            <el-input size="small" v-model="form.telephone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input size="small" v-model="form.email"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select size="small" v-model="form.gender" placeholder="全部" clearable>
              <el-option v-for="item in genderList" :key="item.dictDetailGuid" :label="item.label"
                :value="+item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属角色" prop="roleId">
            <el-select size="small" v-model="form.roleId" placeholder="选择角色">
              <el-option v-for="item in roleList" :key="item.roleGuid" :label="item.roleName"
                :value="item.roleGuid"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属部门" prop="organizeId">
            <el-cascader ref="organRef" size="small" v-model="organize" :options="organList" :props="propss"
              :show-all-levels="false" filterable @change="handleChange"></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="密码" prop="password" v-if="type == 'add'">
            <el-input size="small" v-model="form.password" show-password></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="管理范围" prop="dataRange">
            <el-select size="small" v-model="dataRangeList" clearable multiple>
              <el-option v-for="item in dict.dataRangeList" :key="item.dictDetailGuid" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="dataRangeList.includes('10')">
          <el-form-item label="行政分区" prop="areaCity">
            <el-cascader ref="areaRef" size="small" v-model="form.areaCity" :options="options" :props="props" clearable
              :show-all-levels="false" collapse-tags @change="areaHandleChange"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="dataRangeList.includes('20')"
          :style="(type == 'add' || !dataRangeList.includes('10')) ? '' : 'float:none'">
          <el-form-item label="重点区域" prop="areas">
            <el-select size="small" v-model="form.areas" placeholder="全部" clearable multiple>
              <el-option v-for="item in areasList" :key="item.dictDetailGuid" :label="item.label"
                :value="+item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="description">
            <el-input size="small" type="textarea" :maxlength="500" :rows="3" v-model="form.description"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button size="small" @click="cancel">取 消</el-button>
      <el-button size="small" v-if="type != 'view'" type="primary" @click="sure">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { validatePhone, validateMobile } from "@/common/js/validator.js";
export default {
  props: ['dict'],
  data() {
    return {
      visible: false,
      title: '',
      form: {},
      rules: {
        account: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        roleId: [{ required: true, message: '请选择所属角色', trigger: 'change' }],
        areas: [{ required: true, message: '请选择重点区域', trigger: 'change' }],
        areaCity: [{ required: true, message: '请选择行政区划', trigger: 'change' }],
        organizeId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: validatePhone, trigger: "blur" }],
        telephone: [{ validator: validateMobile, trigger: "blur" }],
      },
      type: '',
      dataRangeAreas: [],   // 行政区划组成
      dataRangeList: [],
      genderList: [],   // 性别
      roleList: [],     // 角色
      organList: [],    // 组织结构
      areasList: [],   // 重点区域
      propss: { expandTrigger: 'hover', label: 'name', value: 'id', children: 'children', checkStrictly: true },
      organize: [],
      options: [],
      props: { expandTrigger: 'hover', label: 'name', value: 'areaCode', children: 'children', checkStrictly: true, multiple: true, emitPath: false },
    };
  },
  methods: {
    showModal(type, row) {
      this.visible = true
      this.type = type
      this.dataRangeList = []
      this.getDictInit()
      this.getRoleList()
      this.getOrganList()
      if (type == 'add') {
        this.title = '新增'
        this.form = {
          "account": "",
          "realName": "",
          "nickName": "",
          "gender": null,
          "telephone": "",
          "email": "",
          "roleId": "",
          "dataRange": "",
          "organizeId": "",
          "isUseage": 1,
          "description": "",
          mobile: '',
          password: '',
          userArea: [],
          areas: [],
          areaCity: []
        }
        this.getAreaTreeInit()
      } else if (type == 'edit') {
        this.title = '编辑'
        this.getAreaTreeInit(row)
        // this.getInfoInit(row.sysUserId)
      } else if (type == 'view') {
        this.title = '详情'
        this.getAreaTreeInit(row)
        //  this.getInfoInit(row.sysUserId)
      }
    },
    // 详情
    getInfoInit(id) {
      this.$api.getUserManageInfo({ id: id }).then(res => {
        if (res && res.code == 200) {
          let data = res.data || {}
          let organize = data.orgCodePath ? data.orgCodePath.split('/') : []
          organize.push(data.organizeId)
          if (organize) {
            this.organize = organize.filter(l => l)
          }
          let dataRangeList = []    // 所属范围绑定值
          let cityItem = data.userArea ? data.userArea.filter(l => l.dataRangeType == '10') : []
          let areaItem = data.userArea ? data.userArea.filter(l => l.dataRangeType == '20') : []
          let areaCity = []
          if (cityItem.length > 0) {
            dataRangeList.push('10')
            cityItem[0].dataRangeAreas.forEach(l => {
              areaCity.push(l.areaCode)
            })
            this.$set(data, 'areaCity', areaCity)
            this.dataRangeAreas = cityItem[0].dataRangeAreas
          }
          let areas = []
          if (areaItem.length > 0) {
            dataRangeList.push('20')
            areaItem.forEach(l => {
              areas.push(l.areaType)
            })
            this.$set(data, 'areas', areas)
          }
          this.dataRangeList = dataRangeList
          this.form = data
        }
      })
    },
    getDictInit() {
      // 性别
      this.$api.getDictDetail({ dicGuid: '1390053212801792' }).then(res => {
        if (res && res.code == 200) {
          let data = res.data || []
          this.genderList = data
        }
      })
      // 重点区域
      this.$api.getDictDetail({ dicGuid: '1391306323524675' }).then(res => {
        if (res && res.code == 200) {
          let data = res.data || []
          this.areasList = data
        }
      })
    },
    // 角色list
    getRoleList() {
      let params = {
        size: 100,
        page: 1
      }
      this.$api.getRoleManageList(params).then((res) => {
        if (res && res.code == 200) {
          let data = res.data || {}
          this.total = data.total || 0
          this.roleList = data.list || []
        }
      })
    },
    // 省市县
    getAreaTreeInit(row) {
      this.$api.getAreaTree().then(res => {
        if (res && res.code == 200) {
          let data = res.data || []
          this.options = data
          if (row) {
            this.getInfoInit(row.sysUserId)
          }
        }
      })
    },
    // 组织机构
    getOrganList() {
      this.$api.getOrganTree().then((res) => {
        if (res && res.code == 200) {
          let data = res.data || []
          this.organList = data
        }
      })
    },
    // 省市县 change
    areaHandleChange(val) {
      console.log(val)
      // console.log(this.$refs.areaRef.getCheckedNodes())
      let _this = this
      if (val) {
        setTimeout(function () {
          let areas = []
          let nodes = _this.$refs.areaRef.getCheckedNodes()
          nodes.forEach(l => {
            let item = {
              areaGuid: l.data.id,
              areaCode: l.data.areaCode
            }
            areas.push(item)
          })
          _this.dataRangeAreas = areas
        }, 100)
      } else {
        this.dataRangeAreas = []
      }
    },
    // 组织机构 change
    handleChange(val) {
      console.log(val)
      this.$refs.organRef.dropDownVisible = false;
      // console.log(this.$refs.organRef.getCheckedNodes())
      if (val) {
        this.form.organizeId = val[val.length - 1]
      } else {
        this.form.organizeId = null
      }
    },
    // 确定
    sure() {
      let userArea = []
      let dataRange = ''
      let areasName = []
      if (this.dataRangeList.includes('10')) {
        userArea.push({
          dataRangeType: 10,
          areaType: null,
          dataRangeAreas: this.dataRangeAreas
        })
        let label = this.dict.dataRangeList.find((val) => {
          return val.value == '10';
        }).label
        dataRange += label

      }
      if (this.dataRangeList.includes('20')) {
        this.form.areas.forEach(el => {
          let item = {
            dataRangeType: 20,
            areaType: el,
            dataRangeAreas: null
          }
          userArea.push(item)
          let name = this.areasList.find((val) => {
            return val.value == el;
          }).label
          areasName.push(name)
        })
        let label = this.dict.dataRangeList.find((val) => {
          return val.value == '20';
        }).label
        label = label + '(' + areasName.join('、') + ')'
        dataRange = dataRange + '、' + label
      }
      this.form.userArea = userArea
      this.form.dataRange = dataRange
      let params = JSON.parse(JSON.stringify(this.form))
      params.areas = null
      params.areaCity = null
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.type == 'add') {
            this.$api.addUserManage(params).then(res => {
              if (res && res.code == 200) {
                this.$notify.success({
                  title: '成功',
                  message: '数据保存成功'
                });
                this.visible = false
                this.$emit('listInit')
              }
            })
          } else if (this.type == 'edit') {
            this.$api.updateUserManage(params).then(res => {
              if (res && res.code == 200) {
                this.$notify.success({
                  title: '成功',
                  message: '数据保存成功'
                });
                this.visible = false
                this.$emit('listInit')
              }
            })
          }
        }
      });
    },
    // 取消
    cancel() {
      this.visible = false;
      this.organize = []
      this.dataRangeList = []
      this.$refs["form"].resetFields();
    },
  }
};
</script>
<style lang="less"></style>
